package org.nimi317.web_gis.global;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import org.nimi317.web_gis.exception.E;
import org.nimi317.web_gis.exception.RException;
import org.nimi317.web_gis.entity.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author thunderobot
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {
    // 全局异常拦截
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> responseException(MethodArgumentNotValidException e) {
        log.info("MethodArgumentNotValidException: {}", e.getMessage());
        String msg = Objects.requireNonNull(e.getFieldError()).getDefaultMessage();
        return R.fail(msg);
    }

    @ExceptionHandler(NotLoginException.class)
    public R<?> handleNotLoginException(Exception e) {
        log.info("NotLoginException: {}", e.getMessage());
        E exception = E.TokenExpiredException;
        return R.fail(exception.getI(), exception.getS());
    }

    @ExceptionHandler(RException.class)
    public R<?> handleRException(RException e) {
        E code = e.getCode();
        log.info("RException: {}", code.getS());
        return R.fail(code.getI(), code.getS());
    }

    @ExceptionHandler(NotRoleException.class)
    public R<?> handleNotRoleException(NotRoleException e) {
        E data = E.UserRoleException;
        String role = e.getRole();
        return R.fail(data.getI(), data.getS() + ":" + role);
    }
}
